import constants from '../js/const';
const formatTime = (date, fmt = 'yyyy-MM-dd') => {
  let o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (let k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};
const formatDate = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  return [year, month, day].map(formatNumber).join('-');
};

const addMonths=function(date=new Date(),months){
  let day = date.getDate(),
      month = date.getMonth(),
      year = date.getFullYear(),
      dateArr = this.formatTime(date,'yyyy-MM-dd hh:mm:ss').split(' ');
  year = year + parseInt((month + months) / 12);
  month = (month + months) % 12;
  month += 1;
  let maxDayCount = new Date(year,month,0).getDate();
  day > maxDayCount ? day = maxDayCount : '';
  month < 10 ? (month = '0' + month) : '';
  day < 10 ? (day = '0' + day) : '';
  return new Date(year + '-' + month + '-' + day + ' ' + dateArr[1]);
};
const addDays = function (date=new Date(),days) {
  date.setDate(date.getDate()+days);
  return date;
};
const storageTimeOut = (hourNum, storageTimeOutFlag) => {
  try {
    let stof = wx.getStorageSync(storageTimeOutFlag);
    if (stof) {
      let nowTime = new Date().getTime();
      return (nowTime - stof) / (1000 * 60 * 60) > hourNum;
    } else {
      return true;
    }
  } catch (e) {
    //TODO 可以考虑反馈信息
    return true;
  }
};
const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};
const getItemValue = (item, field) => {
  let value = item;
  if (typeof field !== 'string' || item.hasOwnProperty(field)) {
    return item[field];
  }
  let props = field.split('.');
  for (let p in props) {
    value = value && value[props[p]];
  }
  return value;
};
const nullToEmpty = (value) => {
  return value ? value : '';
};
const inArray = (key, arr) => {
  let index = -1;
  if (!key || !arr || arr.length === 0) {
    return index;
  }
  arr.forEach(function (r, i) {
    if (r === key) {
      index = i;
      return false;
    }
  });
  return index;
};
const each = (arr, callback) => {
  arr = arr || [];
  try {
    arr.forEach(function (r, i) {
      let rs = callback(i, r);
      if (rs === false) {
        throw Error();
      }
    });
  } catch (e) {
  }
};
const map = (arr, callback) => {
  arr = arr || [];
  let rtnArr = [];
  arr.forEach(function (r, i) {
    let rtnData = callback(r,i);
    if (rtnData) {
      rtnArr.push(rtnData);
    }
  });
  return rtnArr;
};
//类似根据某个字段分组
const groupBy = (arr, filed) => {
  if (!arr || arr.length === 0) {
    return null;
  }
  let fileds = {};
  arr.forEach(frt => {
    let filedType = frt[filed];
    if (!fileds[filedType]) {
      fileds[filedType] = [];
    }
    fileds[filedType].push(frt);
  });
  return fileds;
};
const removeObjectByValue = (arr, values, key) => {
  if (!arr) {
    return;
  }
  for (let i = 0; i < arr.length;) {
    let ele = arr[i];
    if (values instanceof Array) {
      if (inArray(ele[key], values) >= 0) {
        arr.splice(i, 1);
        continue;
      }
    } else {
      if (ele[key] === values) {
        arr.splice(i, 1);
        continue;
      }
    }
    i++;
  }
};
const isFunction = (object) => {
  return typeof object === "function" && typeof object.nodeType !== "number";
};
const containAndIgnoreCase = (str, childStr) => {
  if (str && childStr) {
    if (str.toUpperCase().indexOf(childStr.toUpperCase()) != -1) {
      return true;
    }
  }
  return false;
};
const copy = (o) => {
  let c = {};
  c = JSON.parse(JSON.stringify(o));
  return c;
};
const split = (str) => {
  return str ? str.trim().split(/[\n\s,，;；]/g) : str;
};
const extend = (data, dataExtend) => {
  let res = {};
  for (let key in data) {
    res[key] = data[key];
  }
  for (let key in dataExtend) {
    res[key] = dataExtend[key];
  }
  return res;
};
const trim = (str) => {
  return str ? str.replace(/^\s+|\s+$/gm, '') : str;
};
const getStorageSync = (key) => {
  let str = wx.getStorageSync(key);
  try{
    return str ? Array.isArray(str)||isJson(str)?str: JSON.parse(str) : str;
  }catch(e) {
    return str;
  }

};
const setStorageSync = (key, obj, len = 6) => {
  if (Array.isArray(obj)) {
    if (obj.length > len) {
      obj.splice(obj.length - 1, 1);
    }
  }
  obj && wx.setStorageSync(key, isJson(obj)?JSON.stringify(obj):obj);
};


const isEmptyObject = (e) => {
  let temp;
  for (temp in e)
    return !1;
  return !0
};
const setItemValue = (item, field, value) => {
  if (typeof field !== 'string') {
    return;
  }
  let sumItem = item;
  let props = field.split('.');
  for (let p in props) {
    if (p == props.length - 1) {
      sumItem[props[p]] = value;
    } else {
      if (!sumItem[props[p]]) {
        sumItem[props[p]] = {};
      }
      sumItem = sumItem[props[p]];

    }
  }
};
const mapField = (rows, fields) => {
  let result = [];
  for (let i = 0; i < rows.length; i++) {
    let r = {};
    for (let field in fields) {
      r[field] = rows[i][field];
    }
    result.push(r);
  }
  return result;
};
let promise = function (url, params) {
  params = params || {};
  let isShowLoading = typeof params.isShowLoading === "undefined" ? true : params.isShowLoading;
  if (!isShowLoading && params.loadingMsg) {
    isShowLoading = true;
  }
  isShowLoading && wx.showLoading({title: params.loadingMsg || '请稍后...'});
  url=url.startsWith('/')?url:'/'+url;
  let cookie = wx.getStorageSync(constants.cache_key.sessionid);
  let token="token";
  return new Promise(function (resolve, reject) {
    wx.request({
      url: constants.HOST_NAME + '/wechat' + url,
      data: params,
      header: {
        'content-type': params.isRequestParam ? 'application/x-www-form-urlencoded' : 'application/json' // 默认值
        , cookie: cookie
        ,token:getStorageSync(constants.cache_key.tokenId)
      },
      method: params.method || 'POST',
      success(res) {
        //跟服务器通信是否正常
        isShowLoading && wx.hideLoading();
        if (res.statusCode === 200) {
          //接口返回数据的状态码判断
          if(res.header[token]){
            wx.setStorageSync(constants.cache_key.tokenId, res.header[token]);
          }
          if(res.header["Set-Cookie"]){
            wx.setStorageSync(constants.cache_key.sessionid, res.header["Set-Cookie"]);
          }
          let rs = res.data;
          if (rs.code === 200) {
            //返回接口的正常数据
            resolve(rs);
          } else {
            //显示接口返回的错误信息
            wx.showToast({
              title: rs.message && '未知系统异常' !== rs.message ? rs.message + '' : constants.DEFAULT_ERROR_MSG,
              icon: 'none',
              duration: 1500
            });
            resolve(rs);
          }
        } else {
          let rs = res.data;
          wx.showToast({title:  rs.message && '未知系统异常' !== rs.message ? rs.message + '' : constants.DEFAULT_ERROR_MSG, icon: 'none', duration: 2500});
          resolve();
        }
      },
      fail(e) {
        isShowLoading && wx.hideLoading();
        console.log(e);
        wx.showToast({title: "网络异常", icon: 'none', duration: 2500});
        reject(e)
      }
    });
  })
};

const sort = function (arr, property, sortRule = true) {
  return arr ? arr.sort(compare(property, sortRule)) : arr;
};
const multipleAttrCompare=function(name, minor) {
  return function (o, p) {
    let a, b;
    if (o && p && typeof o === 'object' && typeof p === 'object') {
      a = o[name];
      b = p[name];
      if (a === b) {
        return typeof minor === 'function' ? minor(o, p) : 0;
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1;
      }
      return typeof a < typeof b ? -1 : 1;
    } else {
      throw("error");
    }
  }
};
const compare = function (property, bol) {
  return function (a, b) {
    let value1 = a[property];
    let value2 = b[property];
    let r = bol ? value1 > value2 : value2 <= value1;
    return r ? 1 : -1;
  }
};

let isJson = function (obj) {
  let isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
  return isjson;
};
let isEmail = function (str) {
  if (!str) {
    return true;
  }
  let reg = /^([a-zA-Z0-9_-])+([-.-_A-Za-z0-9])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  let emails = this.split(str);
  let isEmail = true;
  this.each(emails, function (i, email) {
    isEmail = reg.test(email);
    if (!isEmail) {
      return false;
    }
  });
  return isEmail;
};
let isNumber = function (value) {
  if (value === null) {
    return false;
  }
  let patrn = /^(-)?\d+(\.\d+)?$/;
  if (patrn.exec(value)) {
    return true;
  }
  return false;
};
let endWith = function (source, str) {
  let reg = new RegExp(str + "$");
  return reg.test(source);
};
//获取px与rpx之间的比列 
let getRpx=function(height,width) {
  return 750 / width;
};

let contaiLetter=function(str,letter){
  if(!str){
    return false;
  }
  let l = str.substr(0, 1);
  let pattern =/^[a-zA-Z]$/;
  if (l.match(pattern)){
    if (l.toUpperCase() === letter) {
      return true;
    }
  }else{
    let p=pinyin.convertPinyin(l,true);
    if(p){
      let upp=p.substr(0,1);
      if (upp === letter){
        return true;
      }
    }
  }
  return false;
};
let navigateBack=function (pageNme) {
  if(pageNme){
    let pages = getCurrentPages();
  }else{
    wx.navigateBack({delta: 1});
  }
};
let formatName=function(name, startIndex) {
  if (!name) {
    return name;
  }
  if (typeof startIndex === "undefined") {
    startIndex = 1;
  }
  startIndex = Math.min(name.length, startIndex);
  let newStr;
  if (name.length > 0) {
    let char = '';
    for (let i = 0, len = name.length - startIndex; i < len; i++) {
      char += '*';
    }
    newStr = name.substr(0, startIndex) + char;
  } else {
    newStr = name;
  }
  return newStr;
};
let  compareJsonObj= function (obj1, obj2) {
  if(!this.isJson(obj1) || !this.isJson(obj2)) return false;
  let _keys = Object.keys(obj1);
  if(_keys.length != Object.keys(obj2).length) return false;
  for(let _key in obj1){
    if(!obj2.hasOwnProperty(_key)) return false;
    let value1 = obj1[_key];
    let value2 = obj2[_key];
    if(isJson(value1)) return this.compareJsonObj(value1, value2);
    if(String(value1)!=String(value2)) return false;
  }
  return true;
};



module.exports = {
  promise: promise,
  formatTime: formatTime,
  formatDate: formatDate,
  getItemValue: getItemValue,
  nullToEmpty: nullToEmpty,
  inArray: inArray,
  removeObjectByValue: removeObjectByValue,
  each: each,
  forEach: each,
  map: map,
  isFunction: isFunction,
  storageTimeOut: storageTimeOut,
  containAndIgnoreCase: containAndIgnoreCase,
  copy: copy,
  split: split,
  extend: extend,
  trim: trim,
  sort: sort,
  getStorageSync: getStorageSync,
  setStorageSync: setStorageSync,
  isEmptyObject: isEmptyObject,
  setItemValue: setItemValue,
  addMonths:addMonths,
  addDays: addDays,
  isJson: isJson,
  isEmail: isEmail,
  isNumber: isNumber,
  endWith: endWith,
  mapField: mapField,
  groupBy: groupBy,
  getRpx: getRpx,
  multipleAttrCompare:multipleAttrCompare,
  contaiLetter: contaiLetter,
  navigateBack:navigateBack,
  formatName: formatName,
  compareJsonObj:compareJsonObj
};
